<template>
  <div class="app-container">
    <!-- 查询条件 -->
    <div class="filter-container">
      <!-- filter -->
      <el-input
        v-model="listQuery.sno"
        placeholder="学号"
        size="normal"
        :disabled="!isAdmin"
        clearable
        style="width: 200px"
        class="filter-item"
        @keyup.enter.native="handleFilter"
        @clear="handleFilter"
        @blur="handleFilter"
      ></el-input>
      <el-input
        v-model="listQuery.cname"
        placeholder="课程名"
        size="normal"
        clearable
        style="width: 200px"
        class="filter-item"
        @keyup.enter.native="handleFilter"
        @clear="handleFilter"
        @blur="handleFilter"
      ></el-input>

      <el-button
        type="primary"
        class="filter-item"
        size="default"
        icon="el-icon-search"
        style="margin-left: 10px"
        @click="handleFilter"
      >
        点击查询
      </el-button>
      <el-button
        type="primary"
        class="filter-item"
        size="default"
        icon="el-icon-search"
        style="margin-left: 10px"
        v-if="isAdmin"
        @click="handleScore"
      >
        点击新增
      </el-button>
    </div>

    <!-- 列表 -->

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      highlight-current-row
      style="width: 100%"
      @sort-change="sortChange"
      :default-sort="defaultSort"
    >
      <el-table-column
        prop="sno"
        label="学号"
        sortable="custom"
        align="center"
        width="80"
      >
      </el-table-column>
      <el-table-column
        prop="sname"
        label="姓名"
        sortable="custom"
        align="center"
        width="180"
      >
      </el-table-column>
      <el-table-column
        prop="cno"
        label="课程号"
        sortable="custom"
        align="center"
        width="250"
      >
      </el-table-column>
      <!-- 换种方式 ，不使用插槽 -->
      <el-table-column
        label="课程名"
        prop="cname"
        sortable="custom"
        align="center"
        width="150"
      >
      </el-table-column>

      <el-table-column
        label="成绩"
        prop="grade"
        sortable="custom"
        align="center"
        width="150"
      >
        <template slot-scope="{ row: { grade } }">
          <span v-html="grade"></span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="120" v-if="isAdmin">
        <template slot-scope="{ row }">
          <el-button
            type="text"
            size="default"
            @click="handleScore(row)"
            icon="el-icon-edit"
          ></el-button>
          <el-button
            type="text"
            size="default"
            @click="handleDelete(row)"
            icon="el-icon-delete"
            style="color: #ed3333"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 翻页 -->
    <Pagination
      v-show="total > 0"
      :total="total"
      :pageSizes="[10, 20, 30]"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.pageSize"
      @pagination="refresh"
    />

    <!-- 弹框 -->
    <el-dialog
      :title="isUpdate ? '编辑成绩' : '新增成绩'"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
    >
      <el-form :model="dialogForm">
        <el-form-item label="输入学号" :label-width="formLabelWidth">
          <el-input
            v-model="dialogForm.sno"
            autocomplete="off"
            :disabled="isUpdate"
            @blur="handleIsNew"
          ></el-input>
        </el-form-item>
        <el-form-item label="输入课程号" :label-width="formLabelWidth">
          <el-input
            v-model="dialogForm.cno"
            autocomplete="off"
            :disabled="isUpdate"
            @blur="handleIsNew"
          ></el-input>
        </el-form-item>
        <el-form-item label="输入成绩" :label-width="formLabelWidth">
          <el-input v-model="dialogForm.grade" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleUpdateAndInsert"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from "../../components/Pagination/index";
import {
  scoreList,
  insertScore,
  updateScore,
  isNew,
  deleteScore,
} from "@/api/stu";
export default {
  components: { Pagination },
  data() {
    return {
      // 标识是校验是否通过
      pass: false,
      sno: "",
      // 判断是学生还是管理员账户登录
      isAdmin: "",
      // 是新增还是修改
      type: "",
      isUpdate: true,
      // 存在多个table的时候能够对table进行区分
      tableKey: 0,
      // 控制弹框显示
      dialogVisible: false,
      // 弹框数据
      dialogForm: {},
      formLabelWidth: "100px",
      listLoading: false,
      listQuery: {},
      // 表格数据源
      list: [],
      total: 0,
      defaultSort: {},
    };
  },
  mounted() {
    this.getList();
  },
  created() {
    //  对listQuery里的参数做一些解析
    this.parseQuery();
    // 判断是学生还是管理员
    this.isAdmin = this.$store.state.user.roles[0] == "admin" ? true : false;
    if (!this.isAdmin) {
      const sno = this.$store.state.user.sno;
      this.sno = sno;
      this.listQuery.sno = this.sno;
    }
    console.log("sno", this.sno);
  },
  beforeRouteUpdate(to, from, next) {
    console.log(to, from);
    if (to.path === from.path) {
      // 判断query是否相等
      const newQuery = Object.assign({}, to.query);
      const oldQuery = Object.assign({}, from.query);
      if (JSON.stringify(newQuery) !== JSON.stringify(oldQuery)) {
        this.getList();
      }
    }
    next();
  },
  methods: {
    parseQuery() {
      const query = Object.assign({}, this.$route.query);
      let sort = "+sno";
      // 默认参数
      const listQuery = {
        page: 1,
        pageSize: 10,
        sort,
      };
      if (query) {
        query.page && (query.page = +query.page);
        query.pageSize && (query.pageSize = +query.pageSize);
        query.sort && (sort = query.sort);
      }
      const sortSymbol = sort[0];
      const sortColumn = sort.slice(1, sort.length);
      console.log(sortSymbol, sortColumn);
      this.defaultSort = {
        prop: sortColumn,
        order: sortSymbol == "+" ? "ascending" : "descending",
      };
      console.log(this.defaultSort.prop, this.defaultSort.order);
      this.listQuery = {
        ...query,
        ...listQuery,
      };
    },
    // 高亮

    getList() {
      this.listLoading = true;
      scoreList(this.listQuery).then((response) => {
        console.log(response);
        const { list, count } = response.data;
        this.list = list;
        this.total = count;
        this.listLoading = false;
        // 因为有异步的问题，所以需要放在.then里面
        for (let i = 0; i < this.list.length; i++) {
          if (this.list[i].grade <= 60) {
            this.list[
              i
            ].grade = `<span style="color:red">${this.list[i].grade}</span>`;
          }
        }
      });
    },
    // 排序事件
    sortChange(data) {
      console.log("sortChange", data);
      const { prop, order } = data;
      this.sortBy(prop, order);
    },

    sortBy(prop, order) {
      if (order == "ascending") {
        // 在再query里增加个sort参数
        this.listQuery.sort = `+${prop}`;
      } else {
        this.listQuery.sort = `-${prop}`;
      }
      this.handleFilter();
    },
    refresh() {
      this.$router.push({
        path: "/stuScore/table",
        query: this.listQuery,
      });
      // location.reload()
      this.dialogForm = {};
      console.log("刷新了一次");
    },
    handleFilter() {
      console.log("handleFilter", this.listQuery);
      // this.getList();

      this.listQuery.page = 1;
      this.refresh();
    },
    handleScore(row) {
      // console.log(row);
      this.dialogVisible = true;
      if (row.sno) {
        console.log("编辑");
        this.type = "update";
        this.isUpdate = true;
        // 自动填充输入框
        (this.dialogForm.sno = row.sno), (this.dialogForm.cno = row.cno);
        // (this.dialogForm.grade = row.grade);
      } else {
        this.dialogForm = {};
        // console.log('新增');
        this.type = "insert";
        this.isUpdate = false;
      }
      console.log(this.isUpdate);
    },
    handleDelete(row) {
      this.$confirm("确定要删除该成绩吗", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          console.log(row);
          const sno = row.sno;
          const cno = row.cno;
          deleteScore({ sno, cno })
            .then(async (res) => {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              await this.getList();
              await this.refresh();
            })
            .catch((err) => {
              console.log(err);
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // dialog校验 新增、修改成绩
    handleIsNew() {
      const { sno, cno } = this.dialogForm;
      isNew({ sno, cno })
        .then((res) => {
          if (res.code == -1) {
            this.pass = false;
          } else {
            this.pass = true;
          }

          console.log(res);
        })
        .catch((err) => {
          this.pass = false;
          console.log(err);
        });
    },
    async handleUpdateAndInsert() {
      console.log("pass", this.pass);
      if (!this.pass) {
        await this.handleIsNew();
        return;
      }
      console.log(this.dialogForm);
      if (this.type == "insert") {
        await insertScore(this.dialogForm)
          .then((res) => {
            console.log(res);
            this.$message({
              message: "操作成功",
              type: "success",
            });
            if (res.msg == "已经有此记录") {
              updateScore(this.dialogForm)
                .then((res) => {
                  console.log(res);
                  this.$message({
                    message: "操作成功",
                    type: "success",
                  });
                })
                .catch((err) => {
                  console.log(err);
                });
            }
          })
          .catch((err) => {
            console.log(err);
          });
      } else {
        await updateScore(this.dialogForm)
          .then((res) => {
            console.log(res);
            this.$message({
              message: "操作成功",
              type: "success",
            });
          })
          .catch((err) => {
            console.log(err);
          });
      }

      this.dialogVisible = false;

      await this.refresh();
      await this.getList();
    },

    // handleCreate() {
    //   // 页面切换到/book/create 切换到上传图书
    //   this.$router.push("/stuScore/table");
    // },
  },
};
</script>

<style lang="scss" scoped>
.app-container {
  padding-left: 100px;
}
.filter-container {
  margin-left: 80px;
  margin-bottom: 30px;
}
.filter-item {
  margin-right: 20px;
}
</style>